<template>
  <div class="pane-account">
    <el-form :model="account" :rules="accountRules" label-width="120px" status-icon ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { FormRules, ElForm, ElMessage } from 'element-plus'
import { accoutLoginRequest } from '@/service/login/login'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '../../../untils/caceh'
const accountRules: FormRules = {
  name: [
    { required: true, message: '账号是必须的', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,10}$/, message: '账号为3到10位', trigger: 'change' }
  ],
  password: [{ required: true, message: '密码是必须的', trigger: 'blur' }]
}

const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

// 定义数据类型
const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

// 执行登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(isRemPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      // 发送网络请求
      // accoutLoginRequest({ name, password }).then((res) => {
      //   console.log(res)
      // })
      loginStore.loginAccountAction({ name, password }).then((res) => {
        // 判断是否需要记住密码
        if (isRemPwd) {
          localCache.setCache(CACHE_NAME, name)
          localCache.setCache(CACHE_PASSWORD, password)
        }else{
          localCache.deleteCache(CACHE_NAME)
          localCache.deleteCache(CACHE_PASSWORD)
        }
      })
    } else {
      ElMessage.error('验证失败')
    }
  })
}
// 暴露方法
defineExpose({
  loginAction
})
</script>

<style scoped></style>
